<!--suppress TypeScriptUnresolvedReference -->
<script setup lang="ts">
import { useRoute, useRouter } from "vue-router"
import { ref } from "vue"
import { getAllItemDataApi, updateCartDataApi, getCartDataApi, addToCartDataApi } from "@/api/items/items"
import { cartData, itemData, updateCartData } from "@/api/items/types/types"
import { ElMessage } from "element-plus"
import Layout from "@/views/layout/Layout.vue"
const loading = ref(true)
const addButtonFlag = ref(false)
const count = ref(2)
const router = useRouter()
const productId = useRoute().params.productId
const categoryId = useRoute().params.categoryId
const cartItems = ref<cartData[]>([])
const getCartItems = () => {
  loading.value = true
  setTimeout(() => {
    getCartDataApi("HHHH")
      .then((res) => {
        cartItems.value = res.data
        loading.value = false
      })
      .catch((err) => {
        console.log(err)
      })
  }, 3000)
}
getCartItems()
const items = ref<itemData[]>([])
const getItems = () => {
  getAllItemDataApi(productId.toString())
    .then((res) => {
      getCartItems()
      items.value = res.data
      loading.value = false
      if (items.value.length == 0) {
        ElMessage.error("商品待补充！")
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
getItems()
const scrolling = () => {
  count.value += 2
}
const updateCart = (itemId: string, quantity: number, userid: string) => {
  if (quantity == 0) {
    cartItems.value.filter((item) => {
      return item.itemDTO.itemId != itemId
    })
  }
  const data: updateCartData = {
    userid: userid,
    itemid: itemId,
    quantity: quantity
  }
  updateCartDataApi(data).then((res) => {
    if (res.message === "SUCCESS") {
      ElMessage.success("成功修改数量！")
    } else {
      ElMessage.error("修改数量失败！")
    }
  })
}

const formatListPrice = (listPrice) => {
  return "￥" + listPrice.toFixed(2)
}
const gotoItem = (itemId) => {
  router.push("/category/" + categoryId + "/" + productId + "/" + itemId)
}
const addItem = (itemId: string, quantity: number, userid: string) => {
  addButtonFlag.value = true
  setTimeout(() => {
    const data: updateCartData = {
      userid: userid,
      itemid: itemId,
      quantity: quantity
    }
    cartItems.value.at(cartItems.value.findIndex((item) => item.itemDTO.itemId == itemId)).quantity += quantity
    addToCartDataApi(data).then((res) => {
      if (res.message === "SUCCESS") {
        ElMessage.success("成功添加到购物车！")
      } else {
        ElMessage.error("添加到购物车失败！")
      }
      addButtonFlag.value = false
    })
  }, 500)
}
</script>

<template>
  <layout>
    <h1 class="app-title">{{ productId }}</h1>
    <el-skeleton class="animal" animated v-if="loading || items.length == 0" />
    <ul v-infinite-scroll="scrolling" v-else>
      <li v-for="item of items.slice(0, count)" :key="item.itemId">
        <div class="animal">
          <el-image class="pet-photo" :src="item.image" fit="fill" />
          <h2 class="pet-name" @click="gotoItem(item.itemId)">{{ item.itemId }}</h2>
          <p><strong>Product ID:</strong> {{ item.product.productId }}</p>
          <p><strong>Description:</strong> {{ item.attribute1 }} {{ item.attribute2 }} {{ item.product.name }}</p>
          <p
            v-if="
              cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId) === -1 ||
              cartItems.at(cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId)).quantity === 0
            "
          >
            <strong>List Price:</strong>
            <el-text type="warning" size="large">{{ formatListPrice(item.listPrice) }}</el-text>
          </p>
          <p v-else>
            <strong>Total Price:</strong>
            <el-text type="warning" size="large">{{
              formatListPrice(
                item.listPrice * cartItems[cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId)].quantity
              )
            }}</el-text>
          </p>
          <el-button
            type="primary"
            @click="addItem(item.itemId, 1, 'HHHH')"
            :loading="addButtonFlag"
            v-if="
              cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId) === -1 ||
              cartItems.at(cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId)).quantity === 0
            "
            >Add to Cart</el-button
          >
          <el-input-number
            v-model="cartItems[cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId)].quantity"
            v-else
            @change="updateCart(item.itemId, $event, 'HHHH')"
          />
        </div>
      </li>
    </ul>
  </layout>
</template>

<style scoped>
.animal {
  max-width: 650px;
  padding: 20px;
  margin: 30px auto;
  background-color: #fff;
  box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.animal h4 {
  margin: 0 0 6px 0;
}

.pet-photo {
  height: 160px;
  float: left;
  width: 200px;
  margin-right: 15px;
}

.pet-name {
  font-size: 2rem;
  font-weight: normal;
}
.app-title {
  text-align: center;
  font-weight: normal;
  font-size: 2.6rem;
}
</style>
